const util = require('util');
const axios = require('axios');
const {
    wx
} = require('../config/config.js');
const {
    AuthFailed
} = require('../core/httpError.js');

const {
    generateToken
} = require('../core/utils.js');

const {
    User
} = require('../models/user.js');
const { decode } = require('querystring');
class WXManager {
    static async code2Token(code) {
        const url = util.format(wx.loginUrl, wx.appId, wx.appSecret, code);
        console.log('b', url);
        const result = await axios.get(url);
        console.log('c', result.status, result.data.errcode);
        debugger;
        if (result.status !== 200) {
            throw new AuthFailed('openId获取失败');
        }
        const errcode = result.data.errcode;
        if (errcode) { // 正确返回openid 的话，是没有errcode 的
            throw new AuthFailed('openId获取失败:' + errcode);
        }

      // 来查询openid 是否已存在, 存在的话直接生成token 不存在的话 为空,就先存储一下，再生成token。
      let user = await User.getUserByOpenid(result.data.openid);
        if (!user) {
            user = await User.registerByOpenid(result.data.openid)
        }

        return generateToken(user.id, 8);
    }
}

module.exports = {
    WXManager
}